// app 手机登录
const createConfig = require('uni-config-center');

module.exports = {
	// 登陆
	async login() {
		const openid = this.$dx.request.post('openid');
		const access_token = this.$dx.request.post('access_token');
		if (!openid || !access_token) {
			this.$dx.error('openid 或 access_token 不能为空');
		}
		const uniIdConfig = createConfig({
			pluginId: 'uni-id', // 插件id
			// defaultConfig: {},
			customMerge: function (defaultConfig, userConfig) {
				return Object.assign(defaultConfig, userConfig);
			},
		});
		const config = uniIdConfig.config('service.univerify');
		const dCloudAppid = this.$dx.request.appId;
		if (!config || !config.appids.includes(dCloudAppid)) {
			this.$dx.error('未配置一键登录');
		}
		const res = await uniCloud.getPhoneNumber({
			appid: dCloudAppid, // 替换成自己开通一键登录的应用的DCloud appid
			provider: 'univerify',
			apiKey: config.apiKey, // 在开发者中心开通服务并获取apiKey
			apiSecret: config.apiSecret, // 在开发者中心开通服务并获取apiSecret
			access_token,
			openid,
		});
		if (res.success) {
			// 登录
			let user = await this.$dx.service.user.where('mobile', res.phoneNumber).find();
			if (!user) {
				// 创建用户
				return await this.$dx.service.user.createByMobile(res.phoneNumber);
			}
			// 用户已禁用
			if (user.status !== 0) {
				this.$dx.error('用户已禁用');
			}
			// 判断是否有应用权限
			if (user.dcloud_appid.length && !user.dcloud_appid.includes(dCloudAppid)) {
				await this.$dx.service.logs.addLoginLog(user._id, user.username, 'login', 0, user.mobile, user.email);
				this.$dx.error('账号没有应用权限');
			}
			return await this.$dx.service.user.loginByUser(user);
		}
		this.$dx.error('一键登录失败: code=' + res.code);
	},
};
